﻿namespace homework1
{
    
    class MyStack<T>
    {
        public T[] Items;
        private int top;
        private int capacity;

        public MyStack(int capacity)
        {
            this.capacity = capacity;
            this.Items = new T[capacity];
            this.top = -1;
        }

        public void InitStack()
        {
            this.top = -1;
            Array.Clear(Items, 0, Items.Length);
            Console.WriteLine("栈已初始化");
        }

        public void ClearStack()
        {
            this.top = -1;
            Array.Clear(Items, 0, Items.Length);
            Console.WriteLine("栈已清空");
        }

        public bool Push(T item)
        {
            if (top >= capacity - 1)
            {
                Console.WriteLine("栈已满，无法执行入栈操作");
                return false;
            }

            top++;
            Items[top] = item;
            Console.WriteLine($"元素 {item} 已入栈");
            return true;
        }

        public T Pop()
        {
            if (top < 0)
            {
                Console.WriteLine("栈为空，无法执行出栈操作");
                throw new InvalidOperationException("栈为空");
            }

            T item = Items[top];
            Items[top] = default(T);
            top--;
            Console.WriteLine($"元素 {item} 已出栈");
            return item;
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("=== 栈类测试程序 ===");

            // 测试整数栈
            MyStack<int> stack = new MyStack<int>(5);
            stack.InitStack();

            stack.Push(10);
            stack.Push(20);
            stack.Push(30);

            int popped = stack.Pop();
            Console.WriteLine($"出栈的元素: {popped}");

            stack.ClearStack();

            Console.WriteLine("程序执行完毕！");
        }
    }
}